package com.fzj.example.design.prototype;

import sun.nio.cs.US_ASCII;

import java.io.*;
import java.util.function.BiConsumer;

/**
* @Description test-deep copy
* @Author  fanzj
* @Date   2020/5/7 1:28 下午
* @Param
* @Return
* @Exception
*
*/
public class TestCopy {
    public static void main(String[] args) {
        User user = new User();
        user.setAddress("湖北");
        user.setPhone("18971090923");
        user.setAge(24);
        Name name = new Name();
        name.setFirstName("fan");
        name.setSecondName("zaijun");
        user.setName(name);

        Long before = System.currentTimeMillis();
        for (int i = 0; i < 100000; i++) {
            User tmp = copyByNewObject(user);
        }

        long after = System.currentTimeMillis();

        System.out.println(after - before);


    }

    private static <T> T copyByNewObject(T t) {
        ByteArrayOutputStream baos = null;
        ObjectOutputStream oos = null;

        ByteArrayInputStream bais = null;
        ObjectInputStream ois = null;

        T o = null;

        try {
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(t);
            bais = new ByteArrayInputStream(baos.toByteArray());
            ois = new ObjectInputStream(bais);

            o = (T) ois.readObject();

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                baos.close();
                oos.close();
                bais.close();
                ois.close();
            } catch (IOException e) {
                //
            }
        }
        return o;
    }


    /**
     * 深层拷贝 - 需要net.sf.json.JSONObject
     * @param <T>
     * @param obj
     * @return
     * @throws Exception
     */
    /*@SuppressWarnings("unchecked")
    public static <T> T copyByJson(T obj) throws Exception {
        return (T)JSONObject.toBean(JSONObject.fromObject(obj),obj.getClass());
    }*/


    /**
     * 通过Kryo框架深拷贝
     * @param source
     * @return
     */
  /*  public static User copyByKryo(User source){
        Kryo kryo = new Kryo();
        return kryo.copy(source);
    }*/

}
